<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import {
  reqDeleteOne,
  reqDeleteUsers,
  reqGetAllRoles,
  reqSaveOrUpdateUser,
  reqSetRole,
  reqUser,
} from "@/api/acl/user";
import type { Role, SetRole, UserData } from "@/api/acl/user/type.ts";
import { ElMessage } from "element-plus";

let currentPage = ref<number>(1);
let pageSize = ref<number>(5);
let total = ref<number>(5);
let userList = ref<UserData[]>([]);
let isVisible = ref<boolean>(false);
let keyword = ref<string>("");
const getUsers = async () => {
  let result = await reqUser(currentPage.value, pageSize.value, keyword.value);
  if (result.data.code == 200) {
    userList.value = result.data.data.records;
    total.value = result.data.data.total;
  }
};
onMounted(() => {
  getUsers();
});

const handleCurrentChange = () => {
  getUsers();
};
const handleSizeChange = () => {
  getUsers();
};

let userParam = reactive<UserData>({
  username: "",
  password: "",
  name: "",
  roleName: "",
  phone: null,
});
let formRef = ref();
let rules = {
  username: [
    {
      required: true,
      trigger: "blur",
      validator: (rules: string, value: string, callback: any) => {
        if (value.trim().length < 5) {
          callback(new Error("用户名至少5位"));
        } else {
          callback();
        }
      },
    },
  ],
  name: [
    {
      required: true,
      trigger: "blur",
      validator: (rules: string, value: string, callback: any) => {
        if (value.trim().length < 5) {
          callback(new Error("用户名至少5位"));
        } else {
          callback();
        }
      },
    },
  ],
  password: [
    {
      required: true,
      trigger: "blur",
      validator: (rules: string, value: string, callback: any) => {
        if (value.trim().length < 5) {
          callback(new Error("用户名至少5位"));
        } else {
          callback();
        }
      },
    },
  ],
};

const toAddUser = () => {
  Object.assign(userParam, {
    id: "",
    username: "",
    password: "",
    name: "",
    roleName: "",
    phone: null,
  });

  nextTick(() => {
    // 清除校验痕迹和输入痕迹
    formRef.value.clearValidate("username");
    formRef.value.clearValidate("password");
    formRef.value.clearValidate("name");
  });
  isVisible.value = true;
};
const toUpdateUser = async (row: UserData) => {
  Object.assign(userParam, row);

  isVisible.value = true;
};

const confirm = async () => {
  await formRef.value.validate();

  let result = await reqSaveOrUpdateUser(userParam);
  if (result.data.code == 200) {
    ElMessage({
      type: "success",
      message: userParam.id ? "修改成功" : "添加成功",
    });
    await getUsers();
  } else {
    ElMessage({
      type: "error",
      message: userParam.id ? "修改失败" : "添加失败",
    });
  }

  isVisible.value = false;
};

const cancel = () => {
  Object.assign(userParam, {
    id: "",
    username: "",
    password: "",
    name: "",
    roleName: "",
    phone: null,
  });
  isVisible.value = false;
};
// 分配角色
let drawer1 = ref<boolean>(false);
let allRole = ref<Role[]>([]);
let roles = ref<Role[]>([]);

let checkAll = ref<boolean>(false);
let isIndeterminate = ref<boolean>(false); // 中间状态

const setRole = async (row: UserData) => {
  Object.assign(userParam, row);

  let result = await reqGetAllRoles(row.id as number);
  if (result.data.code === 200) {
    allRole.value = result.data.data.allRolesList;
    roles.value = result.data.data.assignRoles;
    drawer1.value = true;
  }
};

const handleCheckAllChange = (val: boolean) => {
  roles.value = val ? allRole.value : [];
  isIndeterminate.value = false;
};
const handleCheckedCitiesChange = (value: Role[]) => {
  const size = value.length;
  checkAll.value = size === allRole.value.length;
  isIndeterminate.value = size > 0 && size < allRole.value.length;
};

const assign = async () => {
  let data: SetRole = {
    userId: userParam.id as number,
    roleIdList: roles.value.map((item) => item.id) as number[],
  };
  let result = await reqSetRole(data);
  if (result.data.code === 200) {
    ElMessage.success("分配成功");
    await getUsers();
    drawer1.value = false;
  } else {
    ElMessage.error("分配失败");
  }
};

// 删除用户
let selectedIds = ref<number[]>([]);
const deleteUser = async (id: number) => {
  let result = await reqDeleteOne(id);
  if (result.data.code === 200) {
    ElMessage.success("删除成功");
    await getUsers();
  }
};

const handleSelectionChange = (value: UserData[]) => {
  selectedIds.value = value.map((item) => item.id) as number[];
  console.log(selectedIds.value);
};

const deleteUsers = async () => {
  let result = await reqDeleteUsers(selectedIds.value);
  if (result.data.code === 200) {
    ElMessage.success("删除成功");
    await getUsers();
  } else {
    ElMessage.error("删除失败");
  }
};
</script>

<template>
  <div>
    <el-card style="height: 80px; margin: 20px 0">
      <el-form inline class="search_form">
        <el-form-item label="用户名">
          <el-input v-model="keyword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getUsers" :disabled="!keyword"
            >搜索</el-button
          >
          <el-button>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <el-button type="primary" @click="toAddUser">添加</el-button>
      <el-button
        type="danger"
        @click="deleteUsers"
        :disabled="!selectedIds.length"
        >批量删除</el-button
      >

      <el-table
        border
        :data="userList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column
          label="用户名字"
          align="center"
          prop="username"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="用户名称"
          align="center"
          prop="name"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="用户角色"
          align="center"
          prop="roleName"
        ></el-table-column>
        <el-table-column
          label="手机"
          align="center"
          prop="phone"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="260px" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="User"
              title="分配权限"
              size="small"
              @click="setRole(row)"
            ></el-button>
            <el-button
              type="warning"
              icon="Edit"
              title="编辑"
              @click="toUpdateUser(row)"
              size="small"
            ></el-button>
            <el-button
              type="danger"
              icon="Delete"
              title="删除"
              size="small"
              @click="deleteUser(row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[4, 6, 8, 10]"
        layout="prev, pager, next, jumper, ->, sizes, total,"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-drawer
      v-model="isVisible"
      :title="userParam.id ? '编辑用户' : '添加用户'"
    >
      <template #default>
        <el-form
          :rules="rules"
          :model="userParam"
          ref="formRef"
          label-width="80px"
          label-position="right"
        >
          <el-form-item label="用户名：" prop="username">
            <el-input v-model="userParam.username"></el-input>
          </el-form-item>
          <el-form-item label="昵称：" prop="name">
            <el-input v-model="userParam.name"></el-input>
          </el-form-item>
          <el-form-item label="密码：" prop="password" v-if="userParam.id">
            <el-input v-model="userParam.password"></el-input>
          </el-form-item>
        </el-form>
      </template>

      <template #footer>
        <el-button type="primary" @click="confirm">确定</el-button>
        <el-button type="info" @click="cancel">取消</el-button>
      </template>
    </el-drawer>

    <el-drawer v-model="drawer1" title="分配角色">
      <template #default>
        <el-form v-model="userParam" label-position="right" label-width="100px">
          <el-form-item label="用户名：">
            <el-input disabled v-model="userParam.username"></el-input>
          </el-form-item>
          <el-form-item label="角色：">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
              >勾选所有职位
            </el-checkbox>
            <!-- 收集的数据是:label，同时放入roles -->
            <el-checkbox-group
              v-model="roles"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="item in allRole"
                :key="item.id"
                :label="item"
                >{{ item.roleName }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button type="primary" @click="assign">确认</el-button>
        <el-button type="info" @click="drawer1 = false">取消</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
.search_form {
  display: flex;
  justify-content: space-between;
}
</style>
